<template>
  <div class="avatar">
    <div>
      <div class="up-div" @click="uploadClick">
        <el-image
          v-if="Url"
          :src="Url"
          :style="{width: imgWidth + 'px', height: imgHeight + 'px'}"
        >
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline" />
          </div>
        </el-image>
        <el-image
          v-else-if="imgUrl && !Url"
          :src="imgUrl"
          :style="{width: imgWidth + 'px', height: imgHeight + 'px'}"
        >
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline" />
          </div>
        </el-image>
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </div>
      <input
        ref="avatarInput"
        type="file"
        class="input-file"
        :accept="'image/*'"
        @change="changeImage($event)"
      >
    </div>
  </div>
</template>
<script>
export default {
  name: 'UpLoadImage',
  props: {
    imgUrl: {
      type: String,
      default: null
    },
    imgWidth: {
      type: Number,
      default: 150
    },
    imgHeight: {
      type: Number,
      default: 150
    }
  },
  data() {
    return {
      Url: null,
      avatar: null,
      file: null
    }
  },
  methods: {
    changeImage: function(e) {
      const file = e.target.files[0]
      this.file = file
      const reader = new FileReader()
      const _this = this
      reader.readAsDataURL(file)
      reader.onload = function(e) {
        // 获取图片尺寸
        _this.Url = this.result
        _this.$emit('getUrl', file)
      }
    },
    init() {
      this.file = null
      this.Url = null
      this.$refs['avatarInput'].value = null
    },
    uploadClick() {
      this.$refs['avatarInput'].click()
    }
  }
}
</script>
<style lang="scss" scope>
.avatar {
  .up-div{
    width: 170px;
    height: 170px;
    padding: 10px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    .avatar-uploader-icon {
      font-size: 40px;
      color: #8c939d;
      width: 150px;
      height: 150px;
      line-height: 150px;
      text-align: center;
    }
    .image-slot{
      text-align: center;
      background-color: #d9d9d9;
      .el-icon-picture-outline{
        font-size: 40px;
        line-height: 150px;
      }
    }
  }
  .input-file {
    width: 40%;
    height: 32px;
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    cursor: pointer;
  }

}
</style>
